package com.cyys.modules.config;

import com.cyys.modules.interceptor.HeaderTokenInterceptor;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Properties;

/**
 * web 配置类
 *
 * @author fengshuonan
 * @date 2016年11月12日 下午5:03:32
 */
@Configuration
@EnableTransactionManagement
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HeaderTokenInterceptor()).addPathPatterns("/api/**").
                excludePathPatterns( "/webjars*", "/v2/**");
    }
//
//    @Override
//    public void addViewControllers(ViewControllerRegistry registry) {
//        registry.addViewController( "/doc" ).setViewName( "classpath:/META-INF/resources/doc.html");
//        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
//    }

    /**
     * 验证码生成相关
     */
    @Bean
    public DefaultKaptcha kaptcha() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.border.color", "105,179,90");
        properties.put("kaptcha.image.width", "200");
        properties.put("kaptcha.image.height", "50");
        //字体颜色
        properties.put("kaptcha.textproducer.font.color", "black");
        //背景颜色渐变，开始颜色
        properties.put("kaptcha.background.clear.from", "white");
        //背景颜色渐变，结束颜色
        properties.put("kaptcha.background.clear.to", "white");
        //文本集合，验证码值从此集合中获取
        properties.put("kaptcha.textproducer.char.string", "1234567890");
        properties.put("kaptcha.textproducer.font.size", "46");
        properties.put("kaptcha.session.key", "code");
        properties.put("kaptcha.textproducer.char.length", "4");
        properties.put("kaptcha.textproducer.font.names", "Wide Latin,Calibri,微软雅黑");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}
